import { DataService } from './../services/data.service';
import { Title } from '@angular/platform-browser';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Location } from '@angular/common';
declare var $: any;
declare var ScrollText: any;
@Component({
  selector: 'app-red-packet',
  templateUrl: './red-packet.component.html',
  styleUrls: ['./red-packet.component.css']
})
export class RedPacketComponent implements OnInit {
  constructor(public fb: FormBuilder,
    public DataService: DataService,
    public route: Location,
    public titleSet: Title) {
  }
  /**活动id */
  public shareDetailRedId: string;
  /**是否验证通过 */
  public reseive: boolean;
  /**是否填写手机号码 */
  public phoneNumB: boolean;
  /** 活动链接id*/
  public shareListRedId: string;
  /**起始地 */
  public startingPlaceName: string;
  /**目的地 */
  public destinationName: string;
  /**货物类型 */
  public category: string;
  /**货物数量 */
  public amount: string;
  /**货物数量单位 */
  public amountUnit: string;
  /**用户真实姓名 */
  public userName: string;

  public mobile: any;
  /**帮抢表单 */
  public user = {
    'mobile': '',
    'code': ''
  };
  public userForm: FormGroup;
  public formErrors = {
    'mobile': '',
    'formError': '',
    'code': ''
  };
  validationMessages = {
    'mobile': {
      'required': '手机号必须输入',
      'pattern': '请输入11位手机号',
    },
    'code': {
      'required': '验证码必须输入',
      'maxlength': '请输入4位验证码',
      'minlength': '请输入4位验证码'
    },
  };
  /**活动是否开启 */
  public isOpen: boolean;
  /**活动是否结束 */
  public isEnd: boolean;
  /**是否自己 */
  public isOwn: boolean;
  /**是否有红包 */
  public isRed: boolean;
  /**是否已经抢过 */
  public isGrab: boolean;
  /**获取的拉米积分 */
  public Yintegral: number;
  /**用户ID */
  public userId: string;
  /**订单短号 */
  public orderNumber: string;
  /**以累计获取的积分 */
  public LJintegral: number;
  /**订单线路 */
  public orderLine: string;
  /**订单单位信息 */
  public orderUnitInfo: string;
  /**总帮抢次数 */
  public totalCount: number;
  /**已帮抢次数 */
  public helpCount: number;
  /**帮抢人列表 */
  public itemlist: Array<string>;
  // public itemlist: [{
  //   /**帮抢人手机 */
  //   phoneNumber: string;
  //   /**帮抢积分 */
  //   BQintegral: number;
  // }];
  /**页面显示表单 */
  public default: boolean;
  /**页面显示获得拉米 */
  public gted: boolean;
  /**页面显示已获得/帮抢成员 */
  public memlist: boolean;
  /**页面显示来晚了已集齐 */
  public lated: boolean;
  /**页面显示活动已结束 */
  public gameover: boolean;


  /**初始化 */
  ngOnInit() {
    this.titleSet.setTitle('来货拉双十一拉米大作战！快来帮我一起抢拉米吧，人人都有份~');
    this.isOpen = true;
    this.default = true;
    this.gted = false;
    this.memlist = false;
    this.lated = false;
    this.gameover = false;

    this.urlUserId();
    this.buildForm();
    this.reseive = this.userForm.valid;
    this.phoneNumB = this.userForm.controls['mobile'].valid;
    // setTimeout(() => {
    //   $("#downloads").popup();
    //   //this.autoScorll();
    //   // this.Qclick();
    // });
  }

  /**获取url参数 */
  urlUserId() {
    var pathUrl = this.route.path();
    /**中文转码 */
    var zhuanma = decodeURIComponent(pathUrl);
    /**匹配？ */
    var wenhao = zhuanma.indexOf("?");
    if (wenhao !== -1) {
      /**？的位置 */
      var pathu = zhuanma.substring(wenhao + 1);
      /**分割成数组 */
      var urlarr = pathu.split("&");
      this.startingPlaceName = urlarr[0].split("=")[1];
      this.destinationName = urlarr[1].split("=")[1];
      this.category = urlarr[2].split("=")[1];
      this.amount = urlarr[3].split("=")[1];
      this.amountUnit = urlarr[4].split("=")[1];
      this.orderNumber = urlarr[5].split("=")[1];
      this.userId = urlarr[6].split("=")[1];
      this.shareListRedId = urlarr[7].split("=")[1];
      this.userName = urlarr[8].split("=")[1];
      // console.log(urlarr, this.startingPlaceName);
    } else {
      this.isOpen = false;
      this.default = false;
      this.gted = false;
      this.memlist = false;
      this.lated = false;
      this.gameover = false;
      $.alert("非法访问~");
      $("#goodsInfo").hide();
      $(".wx-info").css("position", "fixed");
    }

  }
  /**关闭弹窗 */
  Xclose() {
    $.closePopup();
  }
  /**表单 */
  buildForm(): void {
    this.userForm = this.fb.group({
      "mobile": [
        this.user.mobile,
        [
          Validators.required,
          Validators.pattern("^1[345678][0-9]{9}$"),
        ]
      ],
      "code": [
        this.user.code,
        [
          Validators.required,
          Validators.maxLength(4),
          Validators.minLength(4)
        ]
      ]
    });
    this.userForm.valueChanges
      .subscribe(data => this.onValueChanged(data));
    this.onValueChanged();
  }
  onValueChanged(data?: any) {
    if (!this.userForm) {
      return;
    }
    this.reseive = this.userForm.valid;
    this.phoneNumB = this.userForm.controls['mobile'].valid;
    // console.log(this.reseive);
    const form = this.userForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }
  /**无缝向上滚动 */
  autoScorll(): void {
    setTimeout(() => {
      const scroll2 = new ScrollText("slide1", "", "", true, 50, true);
      scroll2.LineHeight = 63;
    })
  }
  /**抢 */
  Qclick() {
    // this.isOwn = true;
    // this.orderNumber = "01711030012";
    // this.userId = "97eec324-ddeb-4a7b-851f-82cdcfae2c86";
    this.DataService.GetMyRedInfo(this.userId, this.orderNumber)
      .subscribe(
      data => {
        // $.alert(data.data);
        this.LJintegral = data.integral;
        this.orderLine = data.orderLine;
        this.orderUnitInfo = data.orderUnitInfo;
        this.totalCount = data.totalCount;
        this.helpCount = data.helpCount;
        var phoneArr = [];
        for (var o = 0; o < data.itemlist.length; o++) {
          phoneArr.push({
            phoneNumber: data.itemlist[o].phoneNumber.substr(0, 3) + "****" + data.itemlist[o].phoneNumber.substr(7),
            integral: data.itemlist[o].integral
          })
        }
        this.itemlist = phoneArr;
        // console.log(phoneArr)
      },
      error => {
        // console.error(error);
        // $.alert(error);
      }
      );
  }

  /**抢拉米 */
  doRegister() {
    if (this.userForm.valid) {
      this.user = this.userForm.value;
      // this.shareListRedId = "1682618b-ec23-49fb-bf2c-85b080ead1a1";
      this.DataService.getRedPacketDetail(this.user.mobile, this.shareListRedId, this.user.code)
        .subscribe(
        data => {
          if (data != null) {
            if (data.isOpen === false) {
              $.alert("很抱歉，本次活动已失效~");
              return;
            } else if (data.isEnd === true) {
              this.default = false;
              this.gted = false;
              this.memlist = false;
              this.lated = false;
              this.gameover = true;
              $("#goodsInfo").hide();
              $(".wx-info").css("position", "fixed");
              return;
            } else if (data.isOwn === true) {
              this.default = false;
              this.gted = false;
              this.memlist = true;
              this.lated = false;
              this.gameover = false;
              this.Qclick();
              // this.autoScorll();
              return;
            } else if (data.isGrab === true) {
              this.default = false;
              this.gted = true;
              this.memlist = false;
              this.lated = false;
              this.gameover = false;
              return;
            } else if (data.isRed === false) {
              this.Qclick();
              this.default = false;
              this.gted = false;
              this.memlist = false;
              this.lated = true;
              this.gameover = false;
              $("#goodsInfo").hide();
              $(".wx-info").css("position", "fixed");
              return;
            } else if (data.data === null) {
              return;
            } else {
              this.Yintegral = data.integral;
              $("#downloads").popup();
              this.default = true;
              this.gted = false;
              this.memlist = false;
              this.lated = false;
              this.gameover = false;
            }
          }
        },
        error => {
          this.formErrors.formError = error.message;
          // console.error(error);
          // $.alert(error);
        }
        );
    } else {
      this.formErrors.formError = "存在不合法的输入项，请检查。";
    }
    // console.log(JSON.stringify(this.user));
  }

  /**手机号获取验证码 */
  getcode() {
    let tel = $('.tel').val();
    let valid = /1[345678][0-9]{9}$/;
    if (!valid.test(tel)) {
      $.alert("请填写正确的手机号~");
    } else {
      this.user = this.userForm.value;
      this.DataService.getCode(this.user.mobile)
        .subscribe(
        data => {
          $.alert("短信验证码发送成功~");
          $('.getCodeBtn').attr('disabled', 'true');
          // $.alert(data.data);
        },
        error => {
          this.formErrors.formError = error.message;
          $('.getCodeBtn').attr('disabled', 'true');
          // console.error(errorMessage);

        }
        );
      
      this.interval();
    }
  }
  /**60秒重发 */
  interval() {
    let i = 60;
    const timer = setInterval(function () {
      $('.getCodeBtn').html(`${i}s后重发`);
      if (i === 0) {
        $('.getCodeBtn').html('获取验证码');
        $('.getCodeBtn').removeAttr('disabled');
        clearInterval(timer);
      }
      i--;
    }, 1000);
  }

}

